package com.peter.popmenudemo;

import androidx.appcompat.app.AppCompatActivity;


import android.os.Bundle;
import android.util.Log;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button bt1 = findViewById(R.id.bt1);
        Button bt2 = findViewById(R.id.bt2);
        Button bt3 = findViewById(R.id.bt3);

        bt1.setOnClickListener(this);
        bt2.setOnClickListener(this);
        bt3.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        PopupMenu popup = new PopupMenu(this, view);//第二个参数是绑定的那个view
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.main, popup.getMenu());

        switch (view.getId()) {
            case R.id.bt1:
                Log.e(TAG, "onClick: bt1", null);
                popup.show();
                break;
            case R.id.bt2:
                Log.e(TAG, "onClick: bt2", null);
                popup.show();
                break;
            case R.id.bt3:
                showPopupMenu(view);
                break;
        }
    }

    private void showPopupMenu(View view) {
        // 这里的view代表popupMenu需要依附的view
        PopupMenu popupMenu = new PopupMenu(MainActivity.this, view);
        // 获取布局文件
        popupMenu.getMenuInflater().inflate(R.menu.sample_menu, popupMenu.getMenu());
        popupMenu.show();
        // 通过上面这几行代码，就可以把控件显示出来了
        popupMenu.setOnMenuItemClickListener(item -> {
            // 控件每一个item的点击事件

//    有时候我们还需要根据不同的条件，显示或隐藏指定的 item，比如在点击第二个按钮的时候隐藏掉“删除歌曲”的选项，只需要添加几行代码：
            popupMenu.getMenu().findItem(R.id.del).setVisible(false);


            return true;
        });
        popupMenu.setOnDismissListener(menu -> {
            // 控件消失时的事件
        });


    }

}